import { ref } from 'vue'

export function useCountdown(duration = 60) {
    const countdown = ref(duration)

    const isEnd = ref(true)

    let timer = 0

    const startCountdown = () => {
        if (!isEnd.value) return
        isEnd.value = false
        clearInterval(timer)
        timer = setInterval(() => {
            countdown.value--
            if (countdown.value <= 0) {
                clearCountdown()
            }
        }, 1000)
    }

    const setDuration = (value) => {
        countdown.value = value
    }

    const clearCountdown = () => {
        clearInterval(timer)
        isEnd.value = true
        countdown.value = duration
    }

    return {
        countdown,
        isEnd,
        startCountdown,
        clearCountdown,
        setDuration
    }
}